using Masuit.Tools;
using Simple.Contracts.Contracts;
using Simple.Contracts.Models;
using Simple.Contracts.Models.Common;
using Simple.Repository;
using Simple.Repository.SimpleEntitys;
using Simple.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Services.Services
{
    /// <summary>
    /// 照护任务服务实现
    /// </summary>
    public class CareMissionService : BaseService, ICareMissionService
    {
        public CareMissionService(FreeSqlCloud freeSqlCloud, CurrentAccount currentAccount) : base(freeSqlCloud, currentAccount) { }

        /// <summary>
        /// 获取照护任务列表
        /// </summary>
        /// <returns>照护任务列表</returns>
        public async Task<Result<List<CareMissionDto>>> List()
        {
            var list = await _simpleFreeSql.Select<CareMission>()
                       .Where(x => x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                       .OrderBy(x => x.Sort)
                       .ToListAsync(x => new CareMissionDto()
                       {
                           Id = x.Id,
                           CompanyId = x.CompanyId,
                           CategorizeId = x.CategorizeId,
                           Name = x.Name,
                           Description = x.Description,
                           IsDailyMission = x.IsDailyMission,
                           DailyMissionStartTime = x.DailyMissionStartTime,
                           DailyMissionEndTime = x.DailyMissionEndTime,
                           DailyMissionExecutionCount = x.DailyMissionExecutionCount,
                           CreateTime = x.CreateTime,
                           CreateBy = x.CreateBy,
                           UpdateTime = x.UpdateTime,
                           UpdateBy = x.UpdateBy,
                           Sort = x.Sort
                       });

            return Result<List<CareMissionDto>>.Success(list);
        }

        /// <summary>
        /// 保存照护任务信息
        /// </summary>
        /// <param name="input">照护任务保存输入参数</param>
        /// <returns>保存结果</returns>
        public async Task<Result<long>> Save(CareMissionSaveInput input)
        {
            try
            {
                if (string.IsNullOrEmpty(input.Name))
                {
                    return Result<long>.FriendlyReminder("照护任务名称不能为空");
                }

                if (input.CategorizeId==0)
                {
                    return Result<long>.FriendlyReminder("请选择照护任务分类");
                }

                long missionId = 0;
                if (input.Id.HasValue && input.Id != 0)
                {
                    // 更新照护任务
                    var mission = await _simpleFreeSql.Select<CareMission>()
                        .Where(x => x.Id == input.Id.Value && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                        .FirstAsync();

                    if (mission == null)
                    {
                        return Result<long>.FriendlyReminder("该照护任务不存在或已被删除");
                    }

                    // 检查名称是否重复
                    var exists = await _simpleFreeSql.Select<CareMission>()
                        .Where(x => x.Name == input.Name && x.Id != input.Id.Value && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                        .AnyAsync();

                    if (exists)
                    {
                        return Result<long>.FriendlyReminder("该照护任务名称已存在");
                    }

                    // 更新数据
                    mission.Name = input.Name;
                    mission.Description = input.Description;
                    mission.IsDailyMission = input.IsDailyMission;
                    mission.DailyMissionStartTime = input.DailyMissionStartTime;
                    mission.DailyMissionEndTime = input.DailyMissionEndTime;
                    mission.DailyMissionExecutionCount = input.DailyMissionExecutionCount;
                    mission.CategorizeId = input.CategorizeId;
                    mission.Sort = input.Sort;
                    mission.UpdateBy = _currentAccount.EmployeeId;
                    mission.UpdateTime = DateTime.Now;
                    mission.DailyMissionStartTimeValue = input.DailyMissionStartTime.IsNullOrEmpty() ? null : int.Parse(input.DailyMissionStartTime!.Replace(":", ""));
                    mission.DailyMissionEndTimeValue = input.DailyMissionEndTime.IsNullOrEmpty() ? null : int.Parse(input.DailyMissionEndTime!.Replace(":", ""));

                    await _simpleFreeSql.Update<CareMission>().SetSource(mission).ExecuteAffrowsAsync();
                    missionId = mission.Id;
                }
                else
                {
                    // 新增照护任务
                    // 检查名称是否重复
                    var exists = await _simpleFreeSql.Select<CareMission>()
                        .Where(x => x.Name == input.Name && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                        .AnyAsync();

                    if (exists)
                    {
                        return Result<long>.FriendlyReminder("该照护任务名称已存在");
                    }

                    var mission = new CareMission()
                    {
                        CompanyId = _currentAccount.CompanyId,
                        CategorizeId = input.CategorizeId,
                        Name = input.Name,
                        Description = input.Description,
                        IsDailyMission = input.IsDailyMission,
                        DailyMissionStartTime = input.DailyMissionStartTime,
                        DailyMissionStartTimeValue = input.DailyMissionStartTime.IsNullOrEmpty() ? null : int.Parse(input.DailyMissionStartTime!.Replace(":", "")),
                        DailyMissionEndTime = input.DailyMissionEndTime,
                        DailyMissionEndTimeValue = input.DailyMissionEndTime.IsNullOrEmpty() ? null : int.Parse(input.DailyMissionEndTime!.Replace(":", "")),
                        DailyMissionExecutionCount = input.DailyMissionExecutionCount,
                        Sort = input.Sort,
                        CreateBy = _currentAccount.EmployeeId,
                        CreateTime = DateTime.Now,
                        UpdateBy = _currentAccount.EmployeeId,
                        UpdateTime = DateTime.Now,
                        IsDelete = 0
                    };

                    missionId = await _simpleFreeSql.Insert<CareMission>(mission).ExecuteIdentityAsync();
                }

                return Result<long>.Success(missionId);
            }
            catch (Exception ex)
            {
                return Result<long>.FriendlyReminder("保存照护任务失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除照护任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Result<bool>> Delete(long id)
        {
            try
            {
                // 软删除照护任务
                await _simpleFreeSql.Update<CareMission>()
                    .Set(x => x.IsDelete, 1)
                    .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                    .Set(x => x.UpdateTime, DateTime.Now)
                    .Where(x => x.CompanyId == _currentAccount.CompanyId && x.Id == id)
                    .ExecuteAffrowsAsync();

                return Result<bool>.Success(true);
            }
            catch (Exception ex)
            {
                return Result<bool>.FriendlyReminder("删除照护任务失败：" + ex.Message);
            }
        }
    }
}